﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Video.Application.Contract.Videos;
using Video.Domain.Shared;
using Video.HttpApi.Host.OPtions;

namespace Video.HttpApi.Host.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class FileController : ControllerBase
    {
        private readonly IVideoService _videoService;
        private readonly VideoFileOptions _videoFileOptions;
        public FileController(IVideoService videoService, VideoFileOptions videoFileOptions)
        {
            _videoService = videoService;   
            _videoFileOptions = videoFileOptions;
        }
        [HttpPost]
        public async Task<string> Upload(IFormFile file, FileType type)
        {
            // 文件存放目录
            var path = Path.Combine(AppContext.BaseDirectory, "wwwroot", type.ToString().ToLower());

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            if(file.Length>_videoFileOptions.MaxFileSize*1024)
            {
                throw new BusinessException("文件超过最大限制");
            }
            var fileName = Guid.NewGuid().ToString("N") + file.FileName;

            using var fileStream = System.IO.File.Create(Path.Combine(path, fileName));

            await file.OpenReadStream().CopyToAsync(fileStream);
            await fileStream.FlushAsync();
            fileStream.Close();

            return type.ToString().ToLower() + "/" + fileName;
        }
        [HttpDelete]
        public async Task DeleteAsync(string path)
        {
            path = Path.Combine(AppContext.BaseDirectory, "wwwroot", path);
            if(Directory.Exists(path))
            {
                if(await _videoService.IsDeleteAsync(path))
                {
                    System.IO.File.Delete(path);
                }
                else
                {
                    throw new BusinessException("您没有权限删除");
                }
            }
        }
    }
    
}
